import { Modal } from 'antd';
import React, { useEffect } from 'react';
import type { ModalProps } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { ProFormProps } from '@ant-design/pro-form';
import type { MenuModalProps } from './data';
import type { EditTreeType } from '../data';

const MenuModal: React.FC<MenuModalProps & ModalProps & ProFormProps> = (props) => {
  const { showEditModal, onFinish, treeData, formRef, itemKey, ...otherProps } = props;
  const [form] = ProForm.useForm();

  // 数据回显
  const echoFrom = (key: string, data: EditTreeType[]) =>
    data?.forEach((item: EditTreeType) => {
      if (item.key === key) {
        form.setFieldsValue({
          name: item.name,
          path: item.path,
          icon: item.icon,
        });
      }
      if (item.children) {
        echoFrom(key, item.children);
      }
    });

  useEffect(() => {
    echoFrom(itemKey, treeData);
  }, [itemKey]);

  return (
    <Modal title="菜单管理" visible={showEditModal} {...otherProps}>
      <ProForm
        layout="horizontal"
        onFinish={(() => {
          return onFinish;
        })()}
        form={form}
      >
        <ProFormText
          width="md"
          name="name"
          label="菜单名"
          tooltip="最长为 24 位"
          placeholder="请输入菜单名"
          rules={[
            { required: true, message: '请输入菜单名!' },
            {
              validator: (rule, value, callback) => {
                if (value.length > 16) {
                  callback('菜单名过长，最长为 16 位');
                } else {
                  callback();
                }
              },
            },
          ]}
        />
        <ProFormText
          width="md"
          name="path"
          label="路由路径"
          placeholder="路由路径，例‘/path/paths’"
          rules={[
            { required: true, message: '请输入路由路径!' },
            {
              validator: (rule, value, callback) => {
                const match = new RegExp('^(/[a-zA-Z]+)+$', 'g');
                if (!match.test(value)) {
                  callback('请输入正确的路由');
                } else {
                  callback();
                }
              },
            },
          ]}
        />
        <ProFormText
          width="md"
          name="icon"
          label="菜单图标"
          placeholder="请输入图标名"
          rules={[
            { required: true, message: '请输入菜单图标!' },
            {
              validator: (rule, value, callback) => {
                const match = new RegExp('^[a-zA-Z]+$', 'g');
                if (!match.test(value)) {
                  callback('请输入正确的图标名');
                } else {
                  callback();
                }
              },
            },
          ]}
        />
      </ProForm>
    </Modal>
  );
};

export default MenuModal;
